package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.MyPagerAdapter;
import com.jdy.haoduoai.adapter.OnPainPointSelectListener;
import com.jdy.haoduoai.adapter.PainPointAdapter;
import com.jdy.haoduoai.adapter.PainPointCustomAdapter;
import com.jdy.haoduoai.enums.SelectionMode;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PainPointItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.view.RippleView.OnRippleCompleteListener;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.jdy.haoduoai.widget.MyViewPager;
import com.jdy.haoduoai.widget.PopWinShare;
import com.nineoldandroids.view.ViewHelper;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

@SuppressLint({"InflateParams", "HandlerLeak"})
public class MyPainPointSelectActivity extends BaseActivity implements
        OnClickListener, OnPageChangeListener {

    @InjectView(id = R.id.select_recom, click = true)
    private RelativeLayout select_recom;
    @InjectView(id = R.id.select_custom, click = true)
    private RelativeLayout select_custom;
    @InjectView(id = R.id.tv_recomHabit)
    private TextView tv_recomHabit;
    @InjectView(id = R.id.tv_customHabit)
    private TextView tv_customHabit;
    @InjectView(id = R.id.beacon)
    private ImageView beacon;
    @InjectView(id = R.id.vpager)
    private MyViewPager vpager;
    @InjectView(id = R.id.bottomlyt)
    private LinearLayout bottomlyts;
    @InjectView(id = R.id.delete, click = true)
    private Button delete;
    @InjectView(id = R.id.select, click = true)
    private Button select;
    @InjectView(id = R.id.toplyt)
    private LinearLayout toplyt;
    @InjectView(id = R.id.bealyt)
    private LinearLayout bealyt;
    @InjectView(id = R.id.commit_btn, click = true)
    private Button mCommitBtn;

    private View page1;
    private View page2;
    private LayoutInflater mInflater;
    private int offset = 0;
    private int currIndex = 0;
    private List<View> views;
    private DisplayMetrics dm = null;
    private int screenW;
    private LayoutParams params;

    // page1
    private LinearLayout emptylayout1;
    private RippleView reloadRippleView1;
    private ListView listView1;
    private ImageView img_defaultfail1;
    private Button btnReload1;

    // page2
    private LinearLayout emptylayout2;
    private RippleView reloadRippleView2;
    private ListView listView2;
    private ImageView img_defaultfail2;
    private Button btnReload2;

    private PainPointAdapter mPainPointAdapter;
    private PainPointCustomAdapter mCustomPainPointAdapter;

    private ArrayList<PainPointItem> mStoryArrayList;
    private ArrayList<PainPointItem> mRadioArrayList;
    private LeUser mLeUser;

    @Override
    @SuppressLint("InflateParams")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.mypainpointselect);

        mTitleText.setTextColor(0xff000000);
        setTitle("习惯养成大纲");

        mSelectedPainPointIds = new ArrayList<Integer>();
        mSelectedPainPointIds2 = new ArrayList<Integer>();

        initUpRightBtn();

        initialize();
        initHandler();
        initListener();
        InitViewPager();
        loadRecomHabitData();
    }

    private void fillRecomHabitList(boolean loadFail) {
        if (mPainPointAdapter == null) {
            if (mStoryArrayList != null && !mStoryArrayList.isEmpty()) {
                mPainPointAdapter = new PainPointAdapter(this, mStoryArrayList);
            } else {
                mPainPointAdapter = new PainPointAdapter(this,
                        new ArrayList<PainPointItem>());
            }

            listView1.setAdapter(mPainPointAdapter);
        } else {
            mPainPointAdapter.notifyDataSetChanged();
        }

        if (loadFail) {
            emptylayout1.setVisibility(View.VISIBLE);
            btnReload1.setVisibility(View.VISIBLE);
            img_defaultfail1.setBackgroundResource(R.drawable.defailt_fail);
        } else {
            if (mPainPointAdapter.getCount() == 0) {
                emptylayout1.setVisibility(View.VISIBLE);
                btnReload1.setVisibility(View.GONE);
                img_defaultfail1.setBackgroundResource(R.drawable.empty_mylove);
            } else {
                emptylayout1.setVisibility(View.GONE);
            }
        }

        mPainPointAdapter.setSelectedList(mSelectedPainPointIds);

        //选中监听事件
        mPainPointAdapter
                .setPainPointSelectListener(new OnPainPointSelectListener() {
                    @Override
                    public void onPainPointSelect(int id, boolean selected) {
                        if (selected) {
                            if (!mSelectedPainPointIds.contains(id)) {
                                mSelectedPainPointIds.add(id);
                            }

                            mCommitBtn.setText("提交好习惯培养计划 (已选 "
                                    + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");

                        } else {
                            if (mSelectedPainPointIds.contains(id)) {
                                int index = mSelectedPainPointIds.indexOf(id);
                                mSelectedPainPointIds.remove(index);
                                mCommitBtn.setText("提交好习惯培养计划 (已选 "
                                        + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");

                            }
                        }
                    }
                });

        //  listView1.setAdapter(mPainPointAdapter);
        listView1.setItemsCanFocus(true);
        listView1.setFocusable(false);
        listView1.setFocusableInTouchMode(false);
        listView1.setClickable(false);

        mPainPointAdapter.notifyDataSetChanged();
    }

    /**
     * 自定义习惯
     *
     * @param loadFail
     */
    private void fillCustomHabitList(boolean loadFail) {
        if (mCustomPainPointAdapter == null) {
            if (mRadioArrayList != null && !mRadioArrayList.isEmpty()) {
                mCustomPainPointAdapter = new PainPointCustomAdapter(this, mRadioArrayList);
            } else {
                mCustomPainPointAdapter = new PainPointCustomAdapter(this,
                        new ArrayList<PainPointItem>());
            }

            listView2.setAdapter(mCustomPainPointAdapter);
        } else {
            if (mRadioArrayList != null) {
                mCustomPainPointAdapter.setData(mRadioArrayList);
            }
            mCustomPainPointAdapter.notifyDataSetChanged();
        }

        if (loadFail) {
            emptylayout2.setVisibility(View.VISIBLE);
            btnReload2.setVisibility(View.VISIBLE);
            img_defaultfail2.setBackgroundResource(R.drawable.defailt_fail);
        } else {
            if (mCustomPainPointAdapter.getCount() == 0) {
                emptylayout2.setVisibility(View.VISIBLE);
                btnReload2.setVisibility(View.GONE);
                img_defaultfail2.setBackgroundResource(R.drawable.empty_mylove);
            } else {
                emptylayout2.setVisibility(View.GONE);
            }
        }

        mCustomPainPointAdapter.setSelectedList(mSelectedPainPointIds2);
        mCustomPainPointAdapter
                .setPainPointSelectListener(new OnPainPointSelectListener() {
                    @Override
                    public void onPainPointSelect(int id, boolean selected) {
                        if (selected) {
                            if (!mSelectedPainPointIds2.contains(id)) {
                                mSelectedPainPointIds2.add(id);
                            }
                            // TODO: 2018/4/10 0010
                            mCommitBtn.setText("提交好习惯培养计划 (已选 "
                                    + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");

                            Log.i("test", "mSelectedPainPointIds2的size是:" + mSelectedPainPointIds2.size());
                        } else {
                            if (mSelectedPainPointIds2.contains(id)) {

                                int index = mSelectedPainPointIds2.indexOf(id);

                                mSelectedPainPointIds2.remove(index);

                                mCommitBtn.setText("提交好习惯培养计划 (已选 "
                                        + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");

                                Log.i("test", "mSelectedPainPointIds2的size是:" + mSelectedPainPointIds2.size());
                            }
                        }
                    }
                });

        //  listView1.setAdapter(mPainPointAdapter);
        listView2.setItemsCanFocus(true);
        listView2.setFocusable(false);
        listView2.setFocusableInTouchMode(false);
        listView2.setClickable(false);
        mCustomPainPointAdapter.notifyDataSetChanged();
    }

    private ArrayList<Integer> mSelectedPainPointIds;
    private ArrayList<Integer> mSelectedPainPointIds2;

    private void loadRecomHabitData() {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess() && Tools.isNotNullStr(result.data)) {

                    mSelectedPainPointIds.clear();

                    if (mStoryArrayList != null) {
                        mStoryArrayList.clear();
                    }

                    ArrayList<PainPointItem> list = (ArrayList<PainPointItem>) JsonSerializer
                            .getInstance().deserialize(result.data, ArrayList.class,
                                    PainPointItem.class);

                    for (PainPointItem ppi : list) {
                        mStoryArrayList.add(ppi);
                        if (ppi.selected) {
                            mSelectedPainPointIds.add(ppi.id);
                        }
                    }

                    mCommitBtn.setText("提交好习惯培养计划 (已选 " + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size())
                            + "个)");


                    fillRecomHabitList(false);
                } else {
                    mStoryArrayList.clear();
                    fillRecomHabitList(true);
                }

                loadCustomHabitData();
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();

                if (mGlobalLeUser != null) {
                    param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                } else {
                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                    if (lu == null) {
                        lu = Tools.restoreLeUser();
                    }
                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                }

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + HttpUtils.GET_PAINPOINT_LIST_GET, param_,
                        HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    private void loadCustomHabitData() {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {

                if (result.isSuccess() && Tools.isNotNullStr(result.data)) {

                    mSelectedPainPointIds2.clear();

                    if (mRadioArrayList != null) {
                        mRadioArrayList.clear();
                    }

                    ArrayList<PainPointItem> list = (ArrayList<PainPointItem>) JsonSerializer
                            .getInstance().deserialize(result.data, ArrayList.class,
                                    PainPointItem.class);

                    for (PainPointItem ppi : list) {
                        mRadioArrayList.add(ppi);
                        if (ppi.enable == 1) {
                            mSelectedPainPointIds2.add(ppi.id);
                        }
                    }

                    mCommitBtn.setText("提交好习惯培养计划 (已选 " + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size())
                            + "个)");


                    fillCustomHabitList(false);
                } else {
                    mRadioArrayList.clear();
                    fillCustomHabitList(true);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();

                if (mGlobalLeUser != null) {
                    param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                } else {
                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                    if (lu == null) {
                        lu = Tools.restoreLeUser();
                    }
                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                }

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + HttpUtils.GET_CUSTOMPAINPOINT_LIST_GET/*HttpUtils.GET_PAINPOINT_LIST_GET*/, param_,
                        HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    private void initialize() {
        mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();

        mStoryArrayList = new ArrayList<>();
        mRadioArrayList = new ArrayList<>();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm); // 得到 屏幕的宽度
        screenW = dm.widthPixels;
        params = beacon.getLayoutParams();
        params.width = screenW / 6; // 设置 控件 cursor 图片的 宽度 是 屏宽的 2/5
        beacon.setLayoutParams(params);

        ViewHelper.setTranslationX(beacon, screenW / 6);

        views = new ArrayList<>(); // 布局集合
        mInflater = LayoutInflater.from(this);

        page1 = mInflater.inflate(R.layout.recomhabitlayout, null);
        emptylayout1 = page1.findViewById(R.id.emptylayout);
        reloadRippleView1 = page1.findViewById(R.id.reloadRippleView);
        img_defaultfail1 = page1.findViewById(R.id.img_defaultfail);
        btnReload1 = page1.findViewById(R.id.reload);
        listView1 = page1.findViewById(R.id.content_views);

        page2 = mInflater.inflate(R.layout.customhabitlayout, null);
        emptylayout2 = page2.findViewById(R.id.emptylayout);
        reloadRippleView2 = page2.findViewById(R.id.reloadRippleView);
        listView2 = page2.findViewById(R.id.content_views);
        img_defaultfail2 = page2.findViewById(R.id.img_defaultfail);
        btnReload2 = page2.findViewById(R.id.reload);

        views.add(page1);
        views.add(page2);

        offset = screenW / 2;
    }

    private void InitViewPager() {
        vpager.setAdapter(new MyPagerAdapter(views));
        vpager.setCurrentItem(0);
    }

    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };
    }

    private void initListener() {
        vpager.setOnPageChangeListener(this);


        reloadRippleView1
                .setOnRippleCompleteListener(new OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        loadRecomHabitData();
                    }
                });

        reloadRippleView2
                .setOnRippleCompleteListener(new OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        loadCustomHabitData();
                    }
                });

        listView1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
            }
        });

        listView2.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                Intent intent = new Intent();
                intent.setClass(MyPainPointSelectActivity.this, AddHabitClockActivity.class);

                intent.putExtra("isedit", true);
                intent.putExtra("custompainpoint", mRadioArrayList.get(arg2));

                startActivityForResult(intent, 100);
            }
        });
    }

    PopWinShare popWinShare;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case 100:
                loadCustomHabitData();
                break;
        }
    }

    class OnClickLintener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layout_addhabit:
                    startActivityForResult(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class), 100);

                    if (popWinShare != null) {
                        popWinShare.dismiss();
                    }
                    break;
                case R.id.layout_edithabit:
                    popWinShare.dismiss();

                    if (!bottomlyts.isShown()) {
                        bottomlyts.setVisibility(View.VISIBLE);
                        img_upright.setImageResource(R.drawable.cancle);

                        mCommitBtn.setVisibility(View.GONE);
                        vpager.setScanScroll(false);
                        if (currIndex == 1 && mCustomPainPointAdapter != null) {
                            mCustomPainPointAdapter.setEditor(true);
                            mCustomPainPointAdapter.notifyDataSetChanged();
                        }

                        toplyt.setVisibility(View.GONE);
                        bealyt.setVisibility(View.GONE);
                        mBackImageButton.setVisibility(View.INVISIBLE);
                    } else {
                        bottomlyts.setVisibility(View.GONE);
                        mCommitBtn.setVisibility(View.VISIBLE);
                        vpager.setScanScroll(true);
                        img_upright.setImageResource(R.drawable.add_habit_icon);

                        if (currIndex == 1 && mCustomPainPointAdapter != null) {
                            mCustomPainPointAdapter.setEditor(false);

                            if (mRadioArrayList != null) {
                                for (PainPointItem item : mRadioArrayList) {
                                    item.isChecked = false;
                                }
                            }
                            mCustomPainPointAdapter.notifyDataSetChanged();
                        }

                        toplyt.setVisibility(View.VISIBLE);
                        bealyt.setVisibility(View.VISIBLE);
                        getbtn_right().setBackgroundResource(R.drawable.edit_btn);
                        mBackImageButton.setVisibility(View.VISIBLE);
                    }

                    break;

                default:
                    break;
            }
        }
    }

    /**
     * 标题栏右边的+号的点击事件,如果当前ViewPager在第0页面时点击直接跳转页面,如果是自定义习惯这弹框
     */
    private void initUpRightBtn() {
        //设置返回键的图标
        mBackImageButton.setImageResource(R.drawable.black_back);
        titleLayout.setBackgroundColor(0xffffffff);

        //设置标题栏右边的+号按钮
        img_upright.setVisibility(View.VISIBLE);
        img_upright.setImageResource(R.drawable.add_habit_icon);
        img_upright.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currIndex == 0) {
                    startActivityForResult(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class), 100);
                    if (popWinShare != null) {
                        popWinShare.dismiss();
                    }
                } else {
                    if (bottomlyts.isShown()) {
                        bottomlyts.setVisibility(View.GONE);
                        mCommitBtn.setVisibility(View.VISIBLE);
                        vpager.setScanScroll(true);
                        img_upright.setImageResource(R.drawable.add_habit_icon);

                        if (currIndex == 1 && mCustomPainPointAdapter != null) {
                            mCustomPainPointAdapter.setEditor(false);

                            if (mRadioArrayList != null) {
                                for (PainPointItem item : mRadioArrayList) {
                                    item.isChecked = false;
                                }
                            }

                            if (mCustomPainPointAdapter.getCount() == 0) {
                                emptylayout2.setVisibility(View.VISIBLE);
                                btnReload2.setVisibility(View.GONE);
                                img_defaultfail2.setBackgroundResource(R.drawable.empty_mylove);
                            } else {
                                emptylayout2.setVisibility(View.GONE);
                            }

                            mCustomPainPointAdapter.notifyDataSetChanged();
                        }

                        toplyt.setVisibility(View.VISIBLE);
                        bealyt.setVisibility(View.VISIBLE);
                        getbtn_right().setBackgroundResource(R.drawable.edit_btn);
                        mBackImageButton.setVisibility(View.VISIBLE);
                    } else {
                        if (popWinShare == null) {
                            OnClickLintener paramOnClickListener = new OnClickLintener();
                            popWinShare = new PopWinShare(MyPainPointSelectActivity.this, paramOnClickListener, Tools.getPixelByDip(MyPainPointSelectActivity.this, 160), Tools.getPixelByDip(MyPainPointSelectActivity.this, 160));
                            popWinShare.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {

                                @Override
                                public void onFocusChange(View v, boolean hasFocus) {
                                    if (!hasFocus) {
                                        popWinShare.dismiss();
                                    }
                                }
                            });
                        }

                        popWinShare.setFocusable(true);
                        popWinShare.showAsDropDown(img_upright, 0, 0);
                        popWinShare.update();
                    }


                }
            }
        });
    }

    private Dialog notificationTipDlg;
    long prelongTim = 0;
    private boolean hasFinish;

    private ArrayList<PainPointItem> mPainPointListSelect;

    public void showNotificationTipDialog() {
        LayoutInflater inflater = getLayoutInflater();
        final View layout = inflater.inflate(R.layout.painpoint_dlg, null);// 获取自定义布局

        TextView tv_babyage = layout.findViewById(R.id.tv_babyage);
        if (tv_babyage != null
                && Tools.isNotEmpty(LeXiaoXiaoBanApp.getInstance().kidAge)) {
            tv_babyage.setText("您的宝贝的年龄是" + LeXiaoXiaoBanApp.getInstance().kidAge
                    + ",");
        }

        notificationTipDlg = new Dialog(this, R.style.custom_dialog);
        notificationTipDlg.setContentView(layout);
        notificationTipDlg.setCancelable(false);
        notificationTipDlg.show();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (hasFinish) {
                    if (notificationTipDlg != null) {
                        notificationTipDlg.dismiss();
                        notificationTipDlg = null;
                    }

                    mPainPointListSelect = new ArrayList<>();
                    for (PainPointItem ppi : mStoryArrayList) {
                        if (mSelectedPainPointIds.contains(ppi.id)) {
                            ppi.selected = true;
                            mPainPointListSelect.add(ppi);
                        }

                        if (mSelectedPainPointIds2.contains(ppi.id)) {
                            ppi.enable = 1;
                            mPainPointListSelect.add(ppi);
                        }
                    }

                    String jsonString = JsonSerializer.getInstance().serialize(
                            mPainPointListSelect);
                    LePreference.getInstance().save("selectedpainpoint", jsonString);

                    Intent intent = new Intent(MyPainPointSelectActivity.this,
                            MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                }
            }
        }, 3000);
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.commit_btn:

                showNotificationTipDialog();

                prelongTim = System.currentTimeMillis();

                hasFinish = false;

                new CustomAsyncTask(this, new IAsyncTask() {
                    @Override
                    public void onRecieveData(Activity activity, ResponseResult result) {
                        hasFinish = true;
                        long curTime = System.currentTimeMillis();

                        if ((curTime - prelongTim) > 3200) {
                            if (notificationTipDlg != null) {
                                notificationTipDlg.dismiss();
                                notificationTipDlg = null;
                            }

                            if (result.isSuccess()) {

                                mPainPointListSelect = new ArrayList<PainPointItem>();
                                for (PainPointItem ppi : mStoryArrayList) {
                                    if (mSelectedPainPointIds.contains(ppi.id)) {
                                        ppi.selected = true;
                                        mPainPointListSelect.add(ppi);
                                    }

                                    if (mSelectedPainPointIds2.contains(ppi.id)) {
                                        ppi.enable = 1;
                                        mPainPointListSelect.add(ppi);
                                    }
                                }

                                String jsonString = JsonSerializer.getInstance().serialize(
                                        mPainPointListSelect);
                                LePreference.getInstance().save("selectedpainpoint", jsonString);

                                Intent intent = new Intent(activity, MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                finish();
                            }
                        }
                    }

                    @Override
                    public ResponseResult doInbackground(Activity activity) {
                        HashMap<String, Object> param_ = new HashMap<String, Object>();
                        String ids = convertList2String(mSelectedPainPointIds);
                        String ids2 = convertList2String(mSelectedPainPointIds2);

                        if (mGlobalLeUser != null) {
                            param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                        } else {
                            LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                            if (lu == null) {
                                lu = Tools.restoreLeUser();
                            }
                            param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                        }

                        if (Tools.isNotEmpty(ids)) {
                            param_.put("habit_ids", ids);
                        }

                        if (Tools.isNotEmpty(ids2)) {
                            param_.put("habit_customized_ids", ids2);
                        }
                        return HttpUtils.startRequest(HttpUtils.API_URL
                                        + HttpUtils.UPDATE_PAINPOINT_POST, param_,
                                HttpUtils.TAG_POST_REQUEST);
                    }
                }).execute();

                break;

            case R.id.select_recom:
                vpager.setCurrentItem(0);
                break;
            case R.id.select_custom:
                vpager.setCurrentItem(1);
                break;
            case R.id.delete:
                //点击删除的操作
                if (currIndex == 0) {
                    deleteStory();
                } else {
                    deleteRadio();
                }
                break;
            case R.id.select:
                if (select.getText().toString().equals("全选")) {
                    if (currIndex == 1 && mCustomPainPointAdapter != null) {
                        mCustomPainPointAdapter.setSelectMode(SelectionMode.SELECT_ALL);
                        mCustomPainPointAdapter.notifyDataSetChanged();
                    }

                    select.setText("取消全选");
                } else if (select.getText().toString().equals("取消全选")) {
                    if (currIndex == 1 && mCustomPainPointAdapter != null) {
                        mCustomPainPointAdapter.setSelectMode(SelectionMode.DESELECT_ALL);
                        mCustomPainPointAdapter.notifyDataSetChanged();
                    }

                    select.setText("全选");
                }
                break;
            default:
                break;
        }
    }

    private String convertList2String(ArrayList<Integer> ids) {
        String result = "";
        if (ids != null) {
            if (ids.size() == 0) {
                return "0";
            }
            int i = 0;
            int size = ids.size();
            for (; i < size; i++) {
                result += ids.get(i);
                if (i != size - 1) {
                    result += ",";
                }
            }
        }
        return result;
    }


    private int flag = 0;

    /**
     * 删除操作
     */
    private void deleteRadio() {
        int selectCount = 0;
        if (mRadioArrayList != null) {
            for (PainPointItem item : mRadioArrayList) {
                if (item != null && item.isChecked) {
                    ++selectCount;
                }
            }
        }

        //有选中的时候弹框
        if (selectCount > 0) {
            CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
                    MyPainPointSelectActivity.this).setMessage("确定删除吗？").setTitle("删除提示")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {

                            if (mRadioArrayList != null && !mRadioArrayList.isEmpty()) {
                                final List<PainPointItem> selectedRecordings = new ArrayList<PainPointItem>();
                                String storyIds = "";

                                //记录要删除的对象集合
                                for (PainPointItem item : mRadioArrayList) {
                                    if (item.isChecked) {
                                        selectedRecordings.add(item);
                                        storyIds += item.id;
                                        storyIds += ",";
                                    }
                                }

                                if (Tools.isNotEmpty(storyIds)) {
                                    storyIds = storyIds.substring(0, storyIds.length() - 1);
                                }

                                if (selectedRecordings.size() > 0) {
                                    showloading("");
                                    final String finalStoryIds = storyIds;
                                    new CustomAsyncTask(MyPainPointSelectActivity.this,
                                            new IAsyncTask() {
                                                @Override
                                                public void onRecieveData(Activity activity,
                                                                          ResponseResult result) {

                                                    //这个地方同时还需要移除mSelectedPainPointIds2的被删除的对象
                                                    //selectedRecordings记录所有需要删除的对象,需要删除mSelectedPainPointIds2的相同对象

                                                    Log.i("test", "mSelectedPainPointIds2的size是:" + mSelectedPainPointIds2.size());

                                                    for (int i = 0; i < selectedRecordings.size(); i++) {
                                                        flag = selectedRecordings.get(i).id;
                                                        for (int j = 0; j < mSelectedPainPointIds2.size(); j++) {
                                                            if (flag == mSelectedPainPointIds2.get(j)) {
                                                                mSelectedPainPointIds2.remove(j);
                                                            }
                                                        }
                                                    }


                                                    Log.i("test", "mSelectedPainPointIds2的size是:" + mSelectedPainPointIds2.size());

                                                    for (PainPointItem rItem : selectedRecordings) {
                                                        mCustomPainPointAdapter.remove(rItem);
                                                    }
                                                    mCustomPainPointAdapter.removeSelection();

                                                    if (Tools.isNotNullStr(result.data)) {
                                                        Toast.makeText(MyPainPointSelectActivity.this,
                                                                result.data, Toast.LENGTH_SHORT).show();
                                                    }

//                                                    Log.i("test", "mSelectedPainPointIds2的size是:" + mSelectedPainPointIds2.size());

                                                    //确定以后的删除按钮,需要同步状态显示值
                                                    mCommitBtn.setText("提交好习惯培养计划 (已选 " + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size())
                                                            + "个)");

                                                    //删除后同时要同步按钮上显示的选中状态的数值
                                                    dismissLoading();
                                                }

                                                @Override
                                                public ResponseResult doInbackground(Activity activity) {
                                                    if (mLeUser == null) {
                                                        mLeUser = Tools.restoreLeUser();
                                                    }

                                                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                                                    param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                                                    return HttpUtils.startRequest(HttpUtils.HOST_API
                                                                    + "/api/2.0/operation/habit/habits_customized/" + finalStoryIds,
                                                            param_, HttpUtils.TAG_DELETE_REQUEST);
                                                }
                                            }).execute();

                                }
                                dialog.dismiss();
                            }
                        }
                    });
            cdb.create().show();
        } else {
            toastShow("未选中任何条目!");
        }
    }

    private void deleteStory() {
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int arg0) {
        Animation animation = null;
        switch (arg0) {
            case 0:
                if (currIndex == 1) {
                    animation = new TranslateAnimation(offset, 0, 0, 0);
                }

                tv_recomHabit.setTextColor(0xff2bacfc);
                tv_customHabit.setTextColor(0xff626262);

                break;
            case 1:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(0, offset, 0, 0);
                }
                tv_recomHabit.setTextColor(0xff626262);
                tv_customHabit.setTextColor(0xff2bacfc);

                break;
        }
        currIndex = arg0;

        if (animation != null) {
            animation.setFillAfter(true);
            animation.setDuration(200);
            beacon.startAnimation(animation);
        }
    }

}
